package com.fenxiangle.yueding.feature.mine.view;


import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.alibaba.sdk.android.vod.upload.VODSVideoUploadCallback;
import com.alibaba.sdk.android.vod.upload.VODSVideoUploadClient;
import com.alibaba.sdk.android.vod.upload.VODSVideoUploadClientImpl;
import com.alibaba.sdk.android.vod.upload.model.SvideoInfo;
import com.alibaba.sdk.android.vod.upload.session.VodHttpClientConfig;
import com.alibaba.sdk.android.vod.upload.session.VodSessionCreateInfo;
import com.aliyun.vod.common.utils.ToastUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fenxiangle.yueding.R;
import com.fenxiangle.yueding.common.widget.dialog.ActionSheetDialog;
import com.fenxiangle.yueding.common.widget.dialog.OnOperItemClickL;
import com.fenxiangle.yueding.entity.bo.DeleteBo;
import com.fenxiangle.yueding.entity.bo.EventEntity;
import com.fenxiangle.yueding.entity.bo.UserCenterBo;
import com.fenxiangle.yueding.entity.bo.UserVideoBo;
import com.fenxiangle.yueding.feature.common.view.MainActivity;
import com.fenxiangle.yueding.feature.common.view.SplashActivity;
import com.fenxiangle.yueding.feature.focus.view.IdentificationActivity;
import com.fenxiangle.yueding.feature.login.view.LoginActivity;
import com.fenxiangle.yueding.feature.mine.view.adapter.VedioAdapter;
import com.fenxiangle.yueding.framework.DataServer;
import com.fenxiangle.yueding.framework.api.UserApi;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.rxbus2.RxBus;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.luck.picture.lib.rxbus2.ThreadMode;
import com.suozhang.framework.component.http.RxDataProcessFactory;
import com.suozhang.framework.component.recyclerview.DividerItemDecoration;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseFragment;
import com.suozhang.framework.utils.SPUtil;
import com.suozhang.framework.widget.SpacesItemDecoration;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.chad.library.adapter.base.listener.SimpleClickListener.TAG;
import static com.fenxiangle.yueding.common.util.FileUtil.getVideoThumb;
import static com.fenxiangle.yueding.common.util.FileUtil.saveBitmap;

/**
 * A simple {@link Fragment} subclass.
 */
public class VedioFragment extends BaseFragment implements BaseQuickAdapter.OnItemChildClickListener, OnOperItemClickL {


    @BindView(R.id.rv_vedio)
    RecyclerView rvVedio;
    private ActionSheetDialog dialog;
    private int mSelectPosition;

    @Override
    public int attachLayoutRes() {
        return R.layout.fragment_vedio;
    }

    private VedioAdapter mVedioAdapter;
    private UserCenterBo userCenterBo;
    private boolean isAdd;
    private boolean isMine;

    public static final String SELECT_KEY = "SELECT_KEY";

    @Override
    protected void initInjector() {

    }

    public static VedioFragment getInstance(UserCenterBo userCenterBo, boolean isAdd, boolean isMine) {
        VedioFragment sf = new VedioFragment();
        sf.userCenterBo = userCenterBo;
        sf.isAdd = isAdd;
        sf.isMine = isMine;
        return sf;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    protected void initView() {
        final String[] stringItems = {"删除"};
        rvVedio.setFocusable(false);
        dialog = new ActionSheetDialog(getActivity(), stringItems, null);
        dialog.isTitleShow(false);
        dialog.setOnOperItemClickL(this);

        rxPermissions = new RxPermissions(getActivity());
        rvVedio.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        rvVedio.addItemDecoration(new SpacesItemDecoration(2, 16, false));
        mVedioAdapter = new VedioAdapter(isAdd);
        mVedioAdapter.setUserCenterBo(userCenterBo);
        mVedioAdapter.bindToRecyclerView(rvVedio);
        List<UserVideoBo> userVideoBos = userCenterBo != null && userCenterBo.getUserVideo() != null ? userCenterBo.getUserVideo() : null;
        mVedioAdapter.setNewData(userVideoBos);
        mVedioAdapter.setOnItemChildClickListener(this);
        mVedioAdapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                if (isMine) {
                    if (dialog != null) dialog.show();
                    mSelectPosition = position;
                }
                return false;
            }
        });
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction("com.emay.power.MyBroadCastReceiver");
            getActivity().registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    List<LocalMedia> selectList = (List<LocalMedia>) intent.getSerializableExtra("status");
                    intent = new Intent(getActivity(), UploadVedioActivity.class);
                    intent.putExtra("userCenterBo", userCenterBo);
                    if (selectList != null && selectList.size() > 0) {
                        intent.putExtra("videoPath", selectList.get(0).getPath());
                        String imagePath = "";
                        if (!TextUtils.isEmpty(selectList.get(0).getPath())) {
                            Bitmap bitmap = getVideoThumb(selectList.get(0).getPath());
                            imagePath = saveBitmap(getActivity(), bitmap);
                            intent.putExtra("imagePath", imagePath);
                        }
                        intent.putExtra("LocalMedia", selectList.get(0));
                    }
                    startActivity(intent);
                }
            }, filter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void initData() {
        if (!RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().register(this);
        }
    }

    @Override
    protected void initEvent() {

    }

    RxPermissions rxPermissions;

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.video_img:
                if (!TextUtils.isEmpty(userCenterBo.getUserVideo().get(position).getVideoUrl())) {
                    Intent intent = new Intent(getActivity(), VideoPlayerActivity.class);
                    intent.putExtra("userCenterBo", userCenterBo);
                    intent.putExtra("videoCoverImg", userCenterBo.getUserVideo().get(position).getVideoCover());
                    intent.putExtra("videoPath", userCenterBo.getUserVideo().get(position).getVideoUrl());
                    intent.putExtra("dec", userCenterBo.getUserVideo().get(position).getVideoDescribe());
                    startActivity(intent);
                }
                break;

            case R.id.btn_show_upload:
                SPUtil.put(getActivity(), SELECT_KEY, position);
                rxPermissions
                        .requestEach(Manifest.permission.CAMERA,
                                Manifest.permission.ACCESS_COARSE_LOCATION,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE
                        )
                        .subscribe(new Consumer<Permission>() {
                            @Override
                            public void accept(Permission permission) throws Exception {
                                if (permission.granted) {
                                    rxPermissions
                                            .request(permission.name)
                                            .subscribe(granted -> {
                                                if (granted) { // Always true pre-M
                                                    // I can control the camera now
                                                } else {
                                                    // Oups permission denied
                                                }
                                            });
                                    return;
                                } else if (permission.shouldShowRequestPermissionRationale) {

                                } else {

                                }
                            } // will emit 2 Permission objects


                        });


                final String[] stringItems = {"本地上传视频", "拍摄视频"};
                dialog = new ActionSheetDialog(getActivity(), stringItems, null);
                dialog.isTitleShow(false);
                dialog.setOnOperItemClickL(new OnOperItemClickL() {
                    @Override
                    public void onOperItemClick(AdapterView<?> parent, View view, int p, long id) {
                        switch (p) {
                            case 0:
                                AM.user().setItemStatus(position);//保存点击状态
                                // 进入相册 以下是例子：用不到的api可以不写
                                PictureSelector.create(getActivity())
                                        .openGallery(PictureMimeType.ofVideo())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                        .theme(R.style.picture_default_style1)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                                        .maxSelectNum(1)// 最大图片选择数量 int
                                        .minSelectNum(1)// 最小选择数量 int
                                        .imageSpanCount(4)  // 每行显示个数 int
                                        .isCamera(true)// 是否显示拍照按钮 true or false
                                        .compress(true)// 是否压缩 true or false
                                        .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                        .forResult(20005);//结果回调onActivityResult code     ;
                                dialog.dismiss();
                                break;
                            case 1:
                                if(!isPermissionOK()){
                                    return;
                                }
                                AM.user().setItemStatus(position);//保存点击状态
                                Intent intent = new Intent(getActivity(), VideoRecordActivity.class);
                                startActivityForResult(intent, 0);
                                dialog.dismiss();
                                break;
                        }
                    }
                });
                dialog.show();


                break;
        }

    }
    private boolean isPermissionOK() {
        boolean isPermissionOK = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || checkPermission();
        if (!isPermissionOK) {
            ToastUtil.showToast(getActivity(), "请开启相机录音权限");
        }
        return isPermissionOK;
    }
    @TargetApi(Build.VERSION_CODES.M)
    private boolean addPermission(List<String> permissionsList, String permission) {
        boolean ret = true;
        if (getActivity().checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
            ret = false;
        }
        return ret;
    }
    @TargetApi(Build.VERSION_CODES.M)
    public boolean checkPermission() {
        boolean ret = true;

        List<String> permissionsNeeded = new ArrayList<String>();
        final List<String> permissionsList = new ArrayList<String>();
        if (!addPermission(permissionsList, Manifest.permission.CAMERA)) {
            permissionsNeeded.add("CAMERA");
        }
        if (!addPermission(permissionsList, Manifest.permission.RECORD_AUDIO)) {
            permissionsNeeded.add("MICROPHONE");
        }
        if (!addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            permissionsNeeded.add("Write external storage");
        }

        if (permissionsNeeded.size() > 0) {
            // Need Rationale
            String message = "You need to grant access to " + permissionsNeeded.get(0);
            for (int i = 1; i < permissionsNeeded.size(); i++) {
                message = message + ", " + permissionsNeeded.get(i);
            }
            // Check for Rationale Option
            if (!getActivity().shouldShowRequestPermissionRationale(permissionsList.get(0))) {

                                getActivity().requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                        0);

            }
            else {
                getActivity().requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                        0);
            }
            ret = false;
        }

        return ret;
    }

    /**
     * 检察每个权限是否申请
     *
     * @param permissions
     * @return true 需要申请权限,false 已申请权限
     */
    private boolean checkEachSelfPermission(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
                return true;
            }
        }
        return false;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            String imagePath = "";
            String videoPath = data.getStringExtra("imagePath");
            if (!TextUtils.isEmpty(videoPath)) {
                Bitmap bitmap = getVideoThumb(videoPath);
                imagePath = saveBitmap(getActivity(), bitmap);
            }
            Intent intent = new Intent(getActivity(), UploadVedioActivity.class);
            intent.putExtra("userCenterBo", userCenterBo);
            intent.putExtra("videoPath", videoPath);
            intent.putExtra("imagePath", imagePath);
            startActivity(intent);
        }
        if (requestCode == 20005) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);

//            Intent intent = new Intent(getActivity(), UploadVedioActivity.class);
//            intent.putExtra("userCenterBo", userCenterBo);
//            intent.putExtra("position",  VedioFragment.this.position);
//            if(selectList!=null&&selectList.size()>0){
//                intent.putExtra("videoPath",selectList.get(0).getPath());
//               String imagePath="";
//                if (!TextUtils.isEmpty(selectList.get(0).getPath())) {
//                    Bitmap bitmap = getVideoThumb(selectList.get(0).getPath());
//                    imagePath = saveBitmap(getActivity(), bitmap);
//                    intent.putExtra("imagePath",imagePath);
//                }
//                intent.putExtra("LocalMedia",selectList.get(0));
//            }
//            startActivity(intent);
//            adapter.setList(selectList);
//            adapter.notifyDataSetChanged();
//
//            for (int i = 0; i < selectList.size(); i++) {
//                if (!TextUtils.isEmpty(selectList.get(i).getPath())) {
//                    mVedioFile = selectList.get(i).getPath();
//                }
//            }
//            if (!TextUtils.isEmpty(mVedioFile)) {
//                Bitmap bitmap = getVideoThumb(mVedioFile);
//                mCoverFile = saveBitmap(this, bitmap);
//            }

        }
    }

    @Override
    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
        List<String> strings = new ArrayList<>();
        DeleteBo deleteBo = new DeleteBo();
        strings.add(userCenterBo.getUserVideo().get(mSelectPosition).getId());
        deleteBo.setVideoIds(strings);
        deleteVedio(deleteBo);
    }

    private void deleteVedio(DeleteBo urls) {
        AM.api().createApiService(UserApi.class)
                .deleteVedio(urls)
                .compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoading(d);
                    }

                    @Override
                    public void onNext(String s) {
                        dismissLoading();
                        showMsg("删除成功!");
                        if (dialog != null) dialog.dismiss();
                        RxBus.getDefault().post(new EventEntity(999, "a"));
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoading();
                        showMsg(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }
}
